define(['app','datetime','pagination','editor','exporting','autocomplete','pagination','filesaver', 'fileupload', 'js/service/agupload','floatlayer'], function( app ) {
	'use strict'; 
	//违规单
	app.controller('Violations', function($scope, dataFactoryCRM, $q,$http, AgUpload) {
		//搜索默认参数
		$scope.salesPerson     = '';
		$scope.Customer        = '';
		$scope.detect          = '';
		$scope.firstTime       = '';
	    $scope.secondTime      = '';
	    $scope.selectss        = '0';
	    $scope.key             = '1';
	    $scope.attribution     = '';
	   	$scope.exportDefault   = -1;
		$scope.conceal         = {child:''};
		$scope.dataEditor      = {array:'',person:'',fine:'',fine_user:''}
		$scope.radio           = {cId:'',person:''}
		$scope.feedback        = {error:'',successful:''}
	    $scope.violationsStatus= [{k: '1',v: '业绩锁定'},{k: '2',v: '罚款'}];
	    $scope.violationsCause = [{k: '1',v: '不签署合同'},{k: '2',v: '暂不寄'},{k:'3',v:'超龄'},{k:'4',v:'虚假身份'}];
		//分页

		$scope.violationsPage  = {pageAll: 1,pageNow: 1,pageSize: 15,k: 3};		
		//首页
		$scope.ViolationsList  = function() {
			//空数据
			$scope.empty 	   = false;
			$scope.exist       = false;
			$scope.pageAppear  = false;
			var _url ='Violations/index?customer='+$scope.Customer+"&sales=" +$scope.salesPerson+"&first_time=" +$scope.firstTime+"&second_time=" +$scope.secondTime +'&p=' + $scope.violationsPage.pageNow + '&psize=' + $scope.violationsPage.pageSize;
			dataFactoryCRM.getDataByAPI(_url).then(function(data){
				$scope.initialize     = data.data;
				if(data.rcode == 1){
					$scope.exist      = $scope.exist;
					$scope.empty      = !$scope.empty;
					if($scope.initialize.page > 1){
						$scope.violationsPage.pageSize = $scope.initialize.psize;
						$scope.violationsPage.pageAll  = $scope.initialize.page;
						$scope.violationsPage.pageNow  = $scope.initialize.p;
					}else{
						$scope.pageAppear = !$scope.pageAppear;
					}
				}else{
					$scope.exist     = !$scope.exist;
					$scope.empty     = $scope.empty;
				}
				if($scope.initialize != undefined){
					$scope.new_list   = $scope.initialize.list;
					for(var i=0;i<$scope.new_list.length;i++){
						if($scope.new_list[i].fine_remark !="" && $scope.new_list[i].fine_remark !=undefined){
							var arr = $scope.new_list[i].fine_remark.split(",");
							if(arr.length > 0){
								if( arr[0].match( /^[\u4E00-\u9FA5]{1,}$/) ){
								   $scope.new_list[i].note = arr[0].substring(0,7) 
								   $scope.new_list[i].Pattribution = arr[1];
								}else{
								   $scope.new_list[i].Pattribution = arr[0].substring(0,7) 
								   $scope.new_list[i].note         = arr[1];
								}			
							}else{
							 	var v = $scope.new_list[i].fine_remark;
								if( v.match( /^[\u4E00-\u9FA5]{1,}$/) ){
								   $scope.new_list[i].note = $scope.new_list[i].fine_remark;
								}else{
								   $scope.new_list[i].Pattribution = $scope.new_list[i].fine_remark.substring(0,7)
								}
							}
						}
					}
				}
			})
    	}
		//初始化页面显示数据（如果是新弹出独立窗口则从父窗口获取）
	    window.loadClientCacheToScope($scope, function(){
	    	$scope.ViolationsList();
	    });
		//违规记录添加加载
		$scope.addShow         = function(){
			$("#frm-add").form('reset');

          	$scope.text_wrong  = true;
			$scope.text_error  = true;
			$scope.radio_err   = false; 

			$scope.$broadcast('angucomplete-alt:clearInput');
			$scope.radio.cId   = '';
			$scope.punishment  = true;
			$scope.Information = false;

			if($("div").hasClass("err401")){
				$scope.error_messges = 1;
			}else{
				$scope.error_messges = 2;
			}

			if($scope.error_messges != 1){
				$('.ui.addShow').modal({
		          observeChanges: true,onApprove: function() {
	      			if( $('#frm-add').form('is valid') && $scope.radio.cId && $scope.radio.cId !="" && $("#attribution").val() !='' && $("#finePubTime").val() !='' ){
		              $scope.violationsAdd( $('#frm-add').serialize() );  
		            }else{
		            	if(!$scope.radio.cId || $scope.radio.cId =="" ){
		            		$scope.radio_err   = true; 
							$scope.radioMsg    = '关联合同不能为空!!!';
							return false;
						}else{
							$scope.radio_err   = false; 
						}	
	            		if($("#attribution").val() !='' ){
							$scope.text_error   = true;
						}else{
							$scope.text_error   = false; 
							$scope.messageText  = '业绩归属不能为空!!!';
							$scope.isError      = true;
							return false;
						}
						if($("#finePubTime").val() !='' ){
							$scope.text_wrong   = true; 
						}else{
							$scope.text_wrong   = false; 
							$scope.messageTexts = '发布时间不能为空!!!';
							$scope.isWrong      = true;
							return false;
						}
		                return false;
		            }
		          }
		        }).modal('show');
			}
	        dataFactoryCRM.getDataByAPI('Violations/addShow').then(function(_d){
	          $scope.finePubTime = _d.today;
	          $scope.completionCustomer = [{}];
 	        })
		}

		//违规记录添加
		$scope.violationsAdd   = function(_d){
			var radio = $scope.radio;
			var _url = 'Violations/violationsAdd?string='+1+'&'+_d+'&person='+radio.person +'&contract='+radio.cId+'&sales_manager='+radio.manager+'&company='+radio.company+'&sales_sector='+radio.sector;
			dataFactoryCRM.getDataByAPI(_url).then(function(data){
				if(data.rcode == 1){
					$('.ui.modal1').modal('show');
				}else{
					$('.ui.modal2').modal('show');
				}
				$scope.Msg = "添加";
				setTimeout(function() {
	                $('.modal1').modal('hide')
	            }, 3000);
	            $scope.ViolationsList();
			})	
		}
		//违规编辑
		$scope.editor_show     = function(){
			$scope.editor      = this.slist;
			//隐藏域赋值
			$("#fineId").val($scope.editor.fine_id);
			$('.ui.editor_show').modal({
	          onApprove: function() {
	          	$("#contractId").val($scope.radio.cId);
	          	if( $('#frm-save').form('is valid') ){
	              $scope.violations_editor( $('#frm-save').serialize() );  
	            }else{
	                 return false;
	            }
	          }
	        }).modal('show');
	        dataFactoryCRM.getDataByAPI('Violations/editor_show?customer_id='+$scope.editor.customer_id+'&fine_id='+$scope.editor.fine_id+'&contract_id='+$scope.editor.contract_id).then(function(_d){
	        	if(_d.rcode == 1){
	        		$scope.save_conceal = _d.list;
	        		$scope.save_messges = false;
	        		$scope.save_default = true;
	        	}else{
	        		$scope.save_default = false;
	        		$scope.save_messges = true;
	        	}
 	        })
		}
		$scope.violations_editor= function(_d){
			dataFactoryCRM.postDataByAPI('Violations/violationsEditor',_d).then(function(data){
				  if(data.error){
				  	$('.ui.modal2').modal('show');
				  	$scope.Msg = "此合同已违规,编辑";
				  }else{
				  	if(data.rcode == 1){
						$('.ui.modal1').modal('show');
					}else{
						$('.ui.modal2').modal('show');
					}
					$scope.Msg = "编辑";
				  }   
				setTimeout(function() {
	                $('.time').modal('hide')
	            }, 3000)
	            $scope.ViolationsList();
 	        })
		} 
		//违规取消提醒
		$scope.cancel_show     = function(fId,cId){
			$(".ui.remind").modal('show');
			$scope.cancel_fId = fId;
			$scope.cancel_cId = cId;
		}
		//解除违规合同
		$scope.cancel          = function(){
			dataFactoryCRM.getDataByAPI("Violations/cancel?contract="+$scope.cancel_cId+"&fine="+$scope.cancel_fId).then(function(data){
				if(data.rcode == 1){
					$('.ui.modal1').modal('show');
				}else{
					$('.ui.modal2').modal('show');
				}
				$scope.Msg = "取消";
				setTimeout(function() {
	                $('.modal1').modal('hide')
	            }, 3000);
	            $scope.ViolationsList();
			})	
		}
		//查看违规消息
		$scope.view            = function(key){
			$scope.history     = this.slist;
			$('.ui.view').modal('show');
		}
		//自动补全验证
		$scope.customer_change = function($item){
			$scope.detect = $item;
			$scope.$watch('detect',function(newvalue,oldvalue){
				if(newvalue != ''){
		          dataFactoryCRM.getDataByAPI('Violations/violationsCustomer?message=' + newvalue)
		          .then(function(d){
		          	if(d.rcode == 1){
		          		$scope.completionCustomer = d.customer;
		          	}else{
		          		$scope.completionCustomer = [{}];
		          	}      
		          });
		        }
			});
		}

		//自动补全返回值 -> 赋值隐藏域
		$scope.returnCustomer  = function(_d){
			$scope.Information = false;
			if(_d){
				$scope.feedback.successful  = 1;
				for(var i=0;i<_d.description.child.length;i++){ _d.description.child[i].mount = parseInt(_d.description.child[i].mount);}
				$scope.conceal    = _d.description;
				if($scope.conceal.child.length == 0) $scope.empty = false;
				else $scope.empty = true;
			
				$scope.customerId       = $scope.conceal.customer_id;
				$scope.customerNickname = $scope.conceal.nickname;
				$scope.customerPhone    = $scope.conceal.phone;
				$scope.Information      = !$scope.Information;
				$("#customerIdCheck").val($scope.customerId);
			}else{
				//隐藏域赋值
				if($("#customerIdCheck").val() == ''){
					$("#customerIdCheck").val("");
				}else{
					$("#customerIdCheck").val("-1");
				}
				$scope.conceal        = '';
			}
		}
	
		//导出违规记录
		$scope.export_excel    = function(key){
			if(key!=-1)
				 var _url = "Violations/export_excel?customer="+$scope.Customer+'&sales='+$scope.salesPerson+'&first_time='+$scope.firstTime+'&second_time='+$scope.secondTime;
			else
				 var _url = "Violations/export_excel?default="+"-1";

			dataFactoryCRM.getDataByAPIS(_url).then(function(matter) {
               var blob = new Blob([matter], {
                    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                });
                saveAs(blob, '违规数据记录表' + '.xls');
            });
		}
		//导入违规单
		$scope.import_excel    = function($fitem){
			AgUpload.add( $fitem );
            AgUpload.setUrl('Violations/import_excel');
            AgUpload.param_add('action','upload');
            AgUpload.start().then( function( data ){
            	$scope.statistical = data.statistical;
            	$('.ui.error_shw').modal('show');
            	if(data.invalid){
            		$scope.invalid = data.invalid;
            	}
	            $scope.ViolationsList();
            });
		}
		//单选
		$scope.CheckRadio      = function(key,person,sector,manager,company,start_time){
			if(start_time != undefined) $("#attribution").val(start_time.substring(0,7));
			$scope.radio.cId    = key;
			$scope.radio.person = person;
			$scope.radio.sector = sector;
			$scope.radio.manager= manager;
			$scope.radio.company= company; 
			if($scope.radio.cId ){
				$scope.radio_err   = false; 
			}else{
				$scope.radio_err   = true; 
				$scope.radioMsg    = '关联合同不能为空!!!';
			}
		}
		//时间样式检测
		$scope.check_time      = function(){
			if($scope.theme_check > 0){
				$("#themeCheck").removeClass('error');
				 $scope.myObj = {
			        "background": "white",
			        "color": "#000",  
			    	"border":"1px solid #cfcfcf"
			    }
			}
			$scope.isError=false;
			$scope.isWarning=false;
			if($("#attribution").val() !='' ){
				$scope.text_error   = true; 
			}else{
				$scope.text_error   = false; 
				$scope.messageText  = '业绩归属不能为空!!!';
				$scope.isError      = true;
			}
			if($("#finePubTime").val() !='' ){
				$scope.text_wrong   = true; 
			}else{
				$scope.text_wrong   = false; 
				$scope.messageTexts = '发布时间不能为空!!!';
				$scope.isWrong      = true;
			}
			if(!$scope.radio.cId || $scope.radio.cId =="" ){
				$scope.radio_err   = true; 
				$scope.radioMsg    = '关联合同不能为空!!!';
				return false;
			}else{
				$scope.radio_err   = false; 
			}
		}
	})
})